package com.rgsx.dao;

import com.rgsx.mapper.UserMapper;
import com.rgsx.pojo.User;
import com.rgsx.redisEntiy.CodeRedisPojo;
import com.rgsx.redisEntiy.UserRedisPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

@Repository
public class UserDao {
    @Autowired
    private UserMapper userMapper;

    @Resource
    private RedisTemplate redisTemplate;

    public User login2(String password,String userName){
        User user = userMapper.selectUserByUsernameAndPassword(userName, password);
        if(user == null){
            return null;
        }
        try {
            redisTemplate.opsForValue().set("user:" + user.getId(),new UserRedisPojo(user,null));
        } catch (Exception e) {
            return user;
        }

        return user;
    }

    public boolean register2(User user){
        try {
            int num = userMapper.insert(user);
            if(num > 0){
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean setRedisPhoneCode(String code,String phone,String uuid){
        try {
            redisTemplate.opsForValue().set("uuid:" + uuid,new CodeRedisPojo(code,phone));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public UserRedisPojo getUserInfo(Long userId){
        UserRedisPojo userRedisPojo = (UserRedisPojo) redisTemplate.opsForValue().get("user:" + userId);
        if(userRedisPojo == null){
            //缓存失效 击穿到数据库
            User user = userMapper.selectById(userId);
            if(user == null)return null;
            userRedisPojo = new UserRedisPojo(user,null);
        }
        return userRedisPojo;
    }

}
